package band.wukong.practice.webservice.kh.sample13;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import javax.xml.ws.Endpoint;

/**
 * 根据wsdl生成的代码，服务端只要接口CalcService。
 *
 * @author wukong(wukonggg@139.com)
 */
public class CalcServer {

    private static final Logger logger = LoggerFactory.getLogger(CalcServer.class);

    public static void main(String[] args) {
//        jaxws();
//        cxfInModeNonContractFirst();
        cxfInModeContractFirst();
        logger.info("Server started.");
        logger.info("WSDL = " + CalcConst.SERVICE_WSDL);
    }

    private static void jaxws() {
        Endpoint.publish(CalcConst.SERVICE_URL, new CalcServiceImpl());
    }

    /**
     * cxf, 非契约优先的方式（框架自己生成的）。wsdl可以看出:
     * 1. wsdl的ServiceName、bindingName等等跟本地wsdl都不同
     * 2. wsdl中的xsd是内嵌的
     */
    private static void cxfInModeNonContractFirst() {
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        factory.setAddress(CalcConst.SERVICE_URL);
        factory.setServiceClass(CalcService.class);
        factory.setServiceBean(new CalcServiceImpl());

        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());

        factory.create();
    }

    /**
     * cxf, 契约优先的方式。wsdl可以看出。
     */
    private static void cxfInModeContractFirst() {
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        factory.setAddress(CalcConst.SERVICE_URL);
        factory.setServiceClass(CalcService.class);
        factory.setServiceBean(new CalcServiceImpl());

        // 需要设置以下两个参数，才能给予契约优先发布。
        factory.setWsdlLocation("META-INF/wsdl/kh/sample13.wsdl");
        factory.setServiceName(new QName(CalcConst.SERVICE_NS, CalcConst.SERVICE_NAME));

        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());

        factory.create();
    }
}
